/*
 * @Author: 赵天天
 * @Date: 2019-04-02 16:10:27
 * @LastEditors: 赵天天
 * @LastEditTime: 2019-05-20 15:08:34
 * @email: dayday_1996@163.com
 * @Descripttion: 系统评分动态分数圈
 */
export default function toCanvas (id, progress, tocolor) {
  // canvas进度条
  var canvas = document.getElementById(id)

  var ctx = canvas.getContext('2d')

  var percent = progress
  // 最终百分比

  var circleX = canvas.width / 2
  // 中心x坐标

  var circleY = canvas.height / 2
  // 中心y坐标

  var radius = 90
  // 圆环半径

  var lineWidth = 20
  // 圆形线条的宽度

  var fontSize = 60 // 字体大小
  var start1 = 0
  var start2 = 0
  // 画圆
  function circle (cx, cy, r) {
    ctx.beginPath()
    // ctx.moveTo(cx + r, cy);
    ctx.lineWidth = lineWidth
    ctx.strokeStyle = '#eee'
    ctx.arc(cx, cy, r, Math.PI * 0, Math.PI * 2)
    ctx.stroke()
  }
  function cubicEaseOut (t, b, c, d) {
    return c * ((t = t / d - 1) * t * t + 1) + b
  };
  // 画弧线
  function sector (cx, cy, r, startAngle, endAngle, anti) {
    ctx.beginPath()
    ctx.lineWidth = lineWidth
    ctx.strokeStyle = 'rgb(255,51,51)'
    var rbb = cubicEaseOut(start1, 255, tocolor[0] - 255, 200)
    var g = cubicEaseOut(start1, 51, tocolor[1] - 51, 200)
    var b = cubicEaseOut(start1, 51, tocolor[2] - 51, 200)
    start1++
    ctx.strokeStyle = 'rgb(' + [parseInt(rbb), parseInt(g), parseInt(b)].join() + ')'
    //  圆弧两端的样式
    ctx.lineCap = 'round'

    // 圆弧
    ctx.arc(
      cx, cy, r,
      (Math.PI * (-0.5)),
      (Math.PI * (-0.5)) + endAngle / 100 * (Math.PI * 2),
      false
    )
    ctx.stroke()
  }

  //  刷新
  function loading () {
    if (process >= percent) {
      clearInterval(circleLoading)
    }

    //  清除canvas内容
    ctx.clearRect(0, 0, circleX * 2, circleY * 2)
    //    中间的字
    ctx.font = fontSize + 'px Microsoft YaHei'
    ctx.textAlign = 'center'
    ctx.textBaseline = 'middle'
    var rbb = cubicEaseOut(start1, 255, tocolor[0] - 255, 200)
    var g = cubicEaseOut(start1, 51, tocolor[1] - 51, 200)
    var b = cubicEaseOut(start1, 51, tocolor[2] - 51, 200)
    start2++
    ctx.fillStyle = 'rgb(' + [parseInt(rbb), parseInt(g), parseInt(b)].join() + ')'
    ctx.fillText(parseFloat(process).toFixed(0), circleX, circleY)
    // 圆形
    circle(circleX, circleY, radius)
    //  圆弧
    sector(circleX, circleY, radius, Math.PI * 2 / 3, process)
    // 两端圆点
    // 控制结束时动画的速度
    if (process / percent > 0.90) {
      process += 0.30
    } else if (process / percent > 0.80) {
      process += 0.55
    } else if (process / percent > 0.70) {
      process += 0.75
    } else {
      process += 1.0
    }
  }

  var process = 0.0 // 进度
  var circleLoading = window.setInterval(function () {
    loading()
  }, 20)
  // 5秒后 去掉上面的定时器
  var t1 = window.setTimeout(refreshCount, 1000 * 2)
  function refreshCount () {
    window.clearInterval(circleLoading)
  }
  // 去掉定时器的方法
  window.clearTimeout(t1)
}
